<template>
  <div class="container">
    

    <!-- 领奖台 -->
    <div class="podium-background">
      <h1 class="title">明星学员</h1>
      <div class="podium">
        <div
          v-for="(user, index) in podiumDisplayOrder"
          :key="index"
          class="podium-item"
          :class="'rank-' + (user.rank)"
        >
          <div class="avatar-wrapper">
            <img
              :src="user.avatar"
              alt="avatar"
              class="avatar"
              @error="handleAvatarError"
            />
            <img v-if="user.rank === 1" src="@/assets/picture/crown.png" alt="crown" class="crown" />
          </div>
          <p class="name">{{ user.name }}</p>
          <span class="rank-number">{{ user.rank }}th</span>
        </div>
      </div>
    </div>

<div class="chart-scroll-wrapper">
  <button class="scroll-btn left" @click="scrollCharts(-1)">‹</button>
  <div class="chart-row" ref="chartRowRef">
    <!-- 新增：学生分析表格 -->
    <div class="chart-card table-card">
      <h2 class="card-title">学生分析</h2>
      <el-input v-model="searchQuery" placeholder="请输入姓名/学号进行搜索" class="search-box" />
      <div class="table-wrapper">
        <el-table :data="filteredStudents" class="custom-table" style="width: 90%">
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column prop="studentName" label="姓名" />
          <el-table-column prop="studentNumber" label="学号" />
          <el-table-column prop="divisionName" label="分班">
            <template #default="scope">
              {{ scope.row.divisionName || '未分班' }}
            </template>
          </el-table-column>
          <el-table-column prop="examTotalScore" label="考试积分" />
          <el-table-column prop="homeworkTotalScore" label="作业积分" />

          <el-table-column prop="finalScore" label="总积分" />
        </el-table>
      </div>
    </div>

    <!-- 课堂活跃度 -->
    <div class="chart-card" ref="activenessChartRef"></div>
    <!-- 作业得分率 -->
    <div class="chart-card" ref="scoreRateChartRef"></div>
    <!-- 作业等级分布 -->
    <div class="chart-card" ref="levelChartRef"></div>
  </div>
  <button class="scroll-btn right" @click="scrollCharts(1)">›</button>
</div>

  </div>
</template>


<script>
import * as echarts from 'echarts';
import { onMounted, ref, computed, nextTick, onBeforeUnmount } from 'vue';
import { useRoute } from 'vue-router';
import {
  getSemesterScore,
  getActiveness,
  getHmkScoreRate,
  getHmkLevel,
} from '@/services/api';
const originalError = console.error;
console.error = function (...args) {
  if (args.some(arg => 
    (typeof arg === 'string' && arg.includes('ResizeObserver')) ||
    (arg instanceof Error && arg.message.includes('ResizeObserver'))
  )) {
    return;
  }
  originalError.apply(this, args);
};
export default {
  setup() {
    const chartRowRef = ref(null);
    const originalErrorHandler = console.error;
    console.error = (...args) => {
      if (args[0] && args[0].includes('ResizeObserver loop')) return;
      originalErrorHandler.apply(console, args);
    };
    const route = useRoute();
    const semesterId = route.query.semesterId || 1;

    const searchQuery = ref('');
    const students = ref([]);
    const topUsers = ref([]);
    const activeness = ref([]);
    const scoreRates = ref([]);
    const levelData = ref([]);
    const handleAvatarError = (event) => {
      event.target.src = require('@/assets/picture/avatar.png');
    };
    const activenessChartRef = ref(null);
    const scoreRateChartRef = ref(null);
    const levelChartRef = ref(null);
    const chartInstances = ref([]);
    let resizeHandler = null;
    const podiumDisplayOrder = computed(() => {
      if (topUsers.value.length < 5) return topUsers.value;
      const users = [...topUsers.value];
      return [
        users[3], // 4th place
        users[1], // 2nd place
        users[0], // 1st place
        users[2], // 3rd place
        users[4], // 5th placeexamTotalScore
      ].map((user, idx) => ({
        ...user,
        rank: idx === 0 ? 4 : idx === 1 ? 2 : idx === 2 ? 1 : idx === 3 ? 3 : 5
      }));
    });
    const filteredStudents = computed(() =>
      students.value.filter(
        (s) => s.studentName.includes(searchQuery.value) || s.studentNumber.includes(searchQuery.value)
      )
    );

    const debounce = (fn, delay) => {
      let timer;
      return (...args) => {
        clearTimeout(timer);
        timer = setTimeout(() => fn.apply(this, args), delay);
      };
    };

    const scrollCharts = (direction) => {
      const container = chartRowRef.value;
      const scrollAmount = container.clientWidth; // 滚动整个容器宽度
      container.scrollBy({
        left: direction * scrollAmount,
        behavior: 'smooth'
      });
    };
const drawCharts = () => {
  chartInstances.value.forEach(chart => chart.dispose());
  chartInstances.value = [];

  setTimeout(() => {
    const commonGrid = {
      top: 120,
      left: 60,
      right: 30,
      // containLabel: true
    };
    const commonXAxis = {
      type: 'category',
      axisLabel: { rotate: 25, color: '#666', fontSize: 12 },
      axisLine: { lineStyle: { color: '#ddd' } },
      axisTick: { show: false }
    };
    const commonYAxis = {
      type: 'value',
      axisLabel: { color: '#666', fontSize: 12 },
      splitLine: { lineStyle: { color: '#f0f0f0' } },
      axisLine: { show: false },
      axisTick: { show: false }
    };

    const charts = [
      {
        ref: activenessChartRef,
        option: {
          backgroundColor: 'transparent',
          grid: commonGrid,
          title: {
            text: '课堂活跃度',
            left: 'center',
            textStyle: { color: '#333', fontSize: 18, fontWeight: 'bold' }
          },
          tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
          xAxis: {
            ...commonXAxis,
            data: activeness.value.map(a => a.username)
          },
          yAxis: commonYAxis,
          series: [
            {
              type: 'bar',
              data: activeness.value.map(a => a.weight_total),
              barWidth: '50%',
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#4facfe' },
                  { offset: 1, color: '#00f2fe' }
                ])
              }
            }
          ]
        }
      },
      {
        ref: scoreRateChartRef,
        option: {
          backgroundColor: 'transparent',
          grid: commonGrid,
          title: {
            text: '作业得分率',
            left: 'center',
            textStyle: { color: '#333', fontSize: 18, fontWeight: 'bold' }
          },
          tooltip: { trigger: 'axis' },
          xAxis: {
            ...commonXAxis,
            data: scoreRates.value.map(s => s.hmk_title)
          },
          yAxis: commonYAxis,
          series: [
            {
              type: 'line',
              smooth: true,
              data: scoreRates.value.map(s => s.score_rate),
              symbol: 'circle',
              symbolSize: 8,
              itemStyle: { color: '#ff6b81' },
              lineStyle: { color: '#ff6b81', width: 3 },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: 'rgba(255,107,129,0.4)' },
                  { offset: 1, color: 'rgba(255,107,129,0)' }
                ])
              }
            }
          ]
        }
      },
      {
        ref: levelChartRef,
        option: {
          backgroundColor: 'transparent',
          grid: commonGrid,
          title: {
            text: '作业成绩分布',
            left: 'center',
            textStyle: { color: '#333', fontSize: 18, fontWeight: 'bold' }
          },
          tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
          legend: {
            top: '10%',
            textStyle: { color: '#666' }
          },
          xAxis: {
            ...commonXAxis,
            data: levelData.value.map(l => l.hmk_title)
          },
          yAxis: commonYAxis,
          series: [
            {
              name: '优秀',
              type: 'bar',
              stack: 'total',
              data: levelData.value.map(l => l.excellentCount),
              barWidth: '50%',
              itemStyle: { color: '#4caf50' }
            },
            {
              name: '良好',
              type: 'bar',
              stack: 'total',
              data: levelData.value.map(l => l.goodCount),
              itemStyle: { color: '#ffca28' }
            },
            {
              name: '及格',
              type: 'bar',
              stack: 'total',
              data: levelData.value.map(l => l.passCount),
              itemStyle: { color: '#29b6f6' }
            },
            {
              name: '不及格',
              type: 'bar',
              stack: 'total',
              data: levelData.value.map(l => l.failCount),
              itemStyle: { color: '#ef5350' }
            },
            {
              name: '未开始',
              type: 'bar',
              stack: 'total',
              data: levelData.value.map(l => l.notStartedCount),
              itemStyle: { color: '#9e9e9e' }
            }
          ]
        }
      }
    ];

    charts.forEach(({ ref, option }) => {
      if (ref.value) {
        const chart = echarts.init(ref.value);
        chart.setOption(option);
        chartInstances.value.push(chart);
      }
    });

    const resizeHandler = debounce(() => {
      requestAnimationFrame(() => {
        chartInstances.value.forEach(chart => {
          try {
            if (!chart.isDisposed()) {
              chart.resize();
            }
          } catch (e) {
            // ignore
          }
        });
      });
    }, 300);

    window.addEventListener('resize', resizeHandler);
  }, 400);
};



    const fetchData = async () => {
      try {
        const scoreRes = await getSemesterScore(semesterId);
        const actRes = await getActiveness(semesterId);
        const rateRes = await getHmkScoreRate(semesterId);
        const levelRes = await getHmkLevel(semesterId);

        if (scoreRes.data.status === 1) {
          students.value = scoreRes.data.data.semDataList;
          topUsers.value = scoreRes.data.data.semTopStuList.map((u) => ({
            name: u.username,
            score: u.score,
            avatar: u.img_url,
          }));
        }
        if (actRes.data.status === 1) activeness.value = actRes.data.data;
        if (rateRes.data.status === 1) scoreRates.value = rateRes.data.data;
        if (levelRes.data.status === 1) levelData.value = levelRes.data.data;

        await nextTick();
        drawCharts();
      } catch (err) {
        console.error("获取数据失败：", err);
      }
    };

    onMounted(fetchData);

    onBeforeUnmount(() => {
      window.removeEventListener('resize', resizeHandler);
      chartInstances.value.forEach(chart => chart.dispose());
    });


    return {
      searchQuery,
      students,
      topUsers,
      filteredStudents,
      activenessChartRef,
      scoreRateChartRef,
      levelChartRef,
      chartRowRef,
      scrollCharts,
      podiumDisplayOrder,
      handleAvatarError
    };
  },
};
</script>

<style scoped>
/* 整体容器 */
.container {
  padding: 40px;
  /* background: #f4f4f4; 浅灰色背景，更柔和 */
  min-height: 100vh;
  box-sizing: border-box;
  color: #333;
  overflow-x: hidden;
}

/* 标题 */
.title {
  text-align: center;
  font-size: 40px;
  font-weight: bold;
  background: linear-gradient(180deg, #ecbb2a, #ba9a38);
  -webkit-background-clip: text;
  color: transparent;
  -webkit-text-fill-color: transparent;
  font-family: '幼圆';
  margin-bottom: 70px;

}

/* 领奖台 */
.podium {
  display: flex;
  justify-content: center;
  align-items: flex-end;
  gap: 30px;
  width: 100%;
  margin: 0 auto 50px auto;
  flex-wrap: wrap;
}

.podium-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
}

/* 领奖台不同层次感 */
.rank-1 {
  height: 160px;
}
.rank-2 {
  height: 140px;
}
.rank-3 {
  height: 130px;
}
.rank-4, .rank-5 {
  height: 120px;
}
.table-card {
  height: 400px;  /* 设定卡片的高度 */
  overflow-y: hidden;  
}

/* 隐藏滚动条，但保持滚动功能 */
.table-wrapper {
  max-height: calc(400px - 60px);  
  overflow-y: scroll;
}

/* 隐藏滚动条（适用于Webkit浏览器，如Chrome，Safari等） */
.table-wrapper::-webkit-scrollbar {
  width: 0px;  /* 不显示水平滚动条 */
  height: 0px;  /* 不显示垂直滚动条 */
}

/* 可选：美化滚动条，如果需要的话 */
.table-wrapper::-webkit-scrollbar-thumb {
  background: #888;  /* 滚动条滑块的颜色 */
  border-radius: 10px;
}

.table-wrapper::-webkit-scrollbar-thumb:hover {
  background: #555; 
}
.avatar-wrapper {
  position: relative;
  width: 100%;
  height: 0;
  top: -40px; /* 头像往上漂浮 */
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  border: 3px solid #fff;
  background: #fff;
  object-fit: cover;
  box-shadow: 0 4px 10px rgba(0,0,0,0.15);
}
.crown {
  position: absolute;
  top: -18px;
  left: 50%;
  transform: translateX(-50%);
  width: 28px;
  animation: crown-float 2s infinite ease-in-out;
}

@keyframes crown-float {
  0%, 100% { transform: translateX(-50%) translateY(0); }
  50% { transform: translateX(-50%) translateY(-8px); }
}

.name {
  margin-top: 10px;
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

.rank-number {
  margin-top: 4px;
  color: #999;
  text-align: center;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 40px;
  background: linear-gradient(180deg, #d4a006, #3a2d07);
  -webkit-background-clip: text;
  color: transparent;
  -webkit-text-fill-color: transparent;
  font-family: '幼圆';
}

/* 选项卡 */
.custom-tabs .el-tabs__header {
  background: transparent;
  border-bottom: 1px solid #ccc; /* 浅灰色分割线 */
}

.custom-tabs .el-tabs__item {
  color: #666;
}

.custom-tabs .el-tabs__item.is-active {
  color: #007bff; /* 蓝色激活状态 */
  font-weight: bold;
}

/* 搜索框 */
.search-box {
  margin: 20px 0;
  width: 90%; /* 宽度撑满父元素 */
  box-sizing: border-box; /* 加上盒模型防止撑爆 */
  margin-left: 5%;

}

/* 表格 */
.custom-table {
  background: #fff;
  border-radius: 10px;
  overflow: hidden;
  /* box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); 更轻的阴影 */
  width:90% ;
  margin-left: 5%;
}

.custom-table th {
  background: #f8f8f8; /* 浅灰色表头背景 */
  color: #666;
}


.custom-table tr:hover td {
  background-color: #f0f3f5; /* 鼠标悬停时的背景色 */
}

/* 修复图表滑动卡片居中 & 使用 scroll-snap */
.chart-scroll-wrapper {
  position: relative;
  overflow: hidden;
  margin-bottom: 40px;
}

.chart-row {
  display: grid;
  grid-auto-flow: column;
  grid-auto-columns: 100%;
  overflow-x: auto;
  scroll-behavior: smooth;
  scroll-snap-type: x mandatory;
  gap: 20px;
  overflow-y: hidden;
}

.chart-card {
  scroll-snap-align: center;
  height: 400px;
  /* background: rgba(30, 30, 30, 0.75); */
  backdrop-filter: blur(8px);
  border-radius: 16px;
  /* box-shadow: 0 6px 20px rgba(0, 0, 0, 0.25); */
  padding: 20px;
}

/* 隐藏滚动条 */
.chart-row::-webkit-scrollbar {
  display: none;
}
.chart-row {
  -ms-overflow-style: none;
  scrollbar-width: none;
}

.scroll-btn {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 36px;
  height: 36px;
  border: none;
  border-radius: 50%;
  /* background: rgba(255, 255, 255, 0.7); */
  color: #333;
  font-size: 20px;
  cursor: pointer;
  z-index: 10;
}
.scroll-btn.left { left: 0px; }
.scroll-btn.right { right: 0px; }
.scroll-btn:hover {
  background: rgba(150, 232, 255, 0.221);
}
.scroll-btn {
  width: 44px;
  height: 44px;
  font-size: 26px;
}
/* 领奖台美化 */
.podium {
  display: flex;
  justify-content: center;
  align-items: flex-end;
  gap: 20px;
  margin: 0 auto 50px auto;
  flex-wrap: wrap;
}

.podium-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  background: #fff;
  border-radius: 10px;
  padding: 50px 10px 0px; /* 顶部留出空间 */
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  width: 80px;
  position: relative; /* 必须relative，才能让内部头像绝对定位 */
}
.podium-item:hover {
  transform: translateY(-6px);
}

/* 柔和渐变色调 */
.rank-1 {
  height: 150px;
  background: linear-gradient(180deg, #ffe28a, #f5c542);
}
.rank-2 {
  height: 130px;
  background: linear-gradient(180deg, #e0e0e0, #b0b0b0);
}
.rank-3 {
  height: 120px;
  background: linear-gradient(180deg, #ffd1a4, #c28840);
}
.rank-4, .rank-5 {
  height: 110px;
  background: #f2f2f2;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  border: 2px solid #eee;
  object-fit: cover;
}

.crown {
  position: absolute;
  top: -50px;
  left: 50%;
  transform: translateX(-50%);
  width: 28px;
  animation: crown-float 2s infinite ease-in-out;
}

@keyframes crown-float {
  0%, 100% { transform: translateX(-50%) translateY(0); }
  50% { transform: translateX(-50%) translateY(-6px); }
}

.name {
  margin-top: 8px;
  font-size: 13px;
  font-weight: bold;
  color: #333;
}
.rank-number {
  font-size: 12px;
  color: #888;
  margin-top: 4px;
}

/* 表格美化 */
.custom-table {
  background: #ffffff;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.06);
  font-size: 14px;
}

.custom-table th {
  background: #f5f7fa;
  color: #666;
  font-weight: 600;
  height: 44px;
}

.custom-table td {
  background: white;
  color: #333;
  height: 42px;
}

.custom-table tr:hover td {
  background-color: #f9fbfc;
}
.podium-background {
  border-radius: 18px;
  width: 100%;
  background: url('@/assets/picture/bacrown.png') center center no-repeat;
  background-size: cover;
  padding: 60px 0 40px;
  box-sizing: border-box;
  position: relative;

  /* 羽化渐变关键 */
  -webkit-mask-image: linear-gradient(to bottom, rgba(0,0,0,1) 60%, rgba(0,0,0,0) 100%);
  mask-image: linear-gradient(to bottom, rgba(0,0,0,1) 60%, rgba(0,0,0,0) 100%);
}

.card-title {
  text-align: center;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
  margin-top: -10px;
}
</style>